package com.clp.protocol.core.client;

import org.springframework.core.GenericTypeResolver;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 客户端事件 监听器
 * @param <T> 监听的事件
 */
@FunctionalInterface
public interface ClientEventListener<T extends ClientEvent<?>> {
    /**
     * 缓存键值对
     */
    @SuppressWarnings("rawtypes")
    Map<Class<? extends ClientEventListener>, Class<? extends ClientEvent>> CACHE_MAP = new ConcurrentHashMap<>(64);
    /**
     * 最大缓存容量
     */
    int MAX_CACHE_MAP_SIZE = 1024;

    @SuppressWarnings({"unchecked", "rawtypes"})
    default Class<T> eventClass() {
        final Class<? extends ClientEventListener> thisClass = this.getClass();

        Class<? extends ClientEvent> eventClass = CACHE_MAP.get(thisClass);
        if (eventClass != null) {
            return (Class<T>) eventClass;
        }
        eventClass = (Class<T>) GenericTypeResolver.resolveTypeArgument(this.getClass(), ClientEventListener.class);

        if (CACHE_MAP.size() <= MAX_CACHE_MAP_SIZE) {
            CACHE_MAP.put(thisClass, eventClass);
        }

        return (Class<T>) eventClass;
    }

    void onEvent(T event);

}
